/*
 * ElementJSonSerializer.java
 * This file contains Boeing intellectual property. It
 * may contain information about Boeing processes that are part of the Company's
 * competitive advantage. Release of this file requires prior approval from
 * Luxoft Management. Copyright (c) 2008, The Boeing Company All Rights Reserved
 */
package json;

import filter.ConversationManager;
import java.io.PrintWriter;
import java.util.Map;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author dakhoa
 * @version 1.0
 */
public class ElementJSonSerializer {

    private static final String INSTANCE_KEY = "_jsonObject";
    private static ElementJSonSerializer instance;
    private JsonArray elements;

    private ElementJSonSerializer() {
    }

    public static synchronized ElementJSonSerializer getInstance() {
        Map flScope = ConversationManager.getInstance().getFlowScope();
        instance = (ElementJSonSerializer) flScope.get(INSTANCE_KEY);
        if (instance == null) {
            instance = new ElementJSonSerializer();
            instance.elements = new JsonArray("elements");
            flScope.put(INSTANCE_KEY, instance);
        }

        return instance;
    }

    public void serialize(PrintWriter writer, ModelAndView mv, boolean isAjxReq) {
        if (isAjxReq) {
            writer.write(serialize2String());
            writer.flush();
            writer.close();

        } else {
            mv.addObject(INSTANCE_KEY, serialize2String());
        }
    }

    public String serialize2String() {
        return elements.toJson();
    }

    public void add(ElementJson... jsons) {
        elements.add(jsons);
    }

    public void add(ElementJson e) {
        elements.add(e);
    }

    public void remove(ElementJson... jsons) {
        for (ElementJson e : jsons) {
            elements.remove(e);
        }
    }
}
